﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class GridLengthConverter : DefaultConverter
    {


        #region public override bool  CanProcess(XamlCodeContext context)
        public override bool CanProcess(XamlCodeContext context)
        {
            Type type = context.Peek.MemberType;
            if (type != null && type.FullName == "System.Windows.GridLength")
                return true;
            return base.CanProcess(context);
        }
        #endregion



        #region protected override CodeExpression  ConvertValue(Type type, object val)
        protected override CodeExpression ConvertValue(Type type, object val)
        {
            string strValue = val.ToString();
            if (strValue == "Auto")
                return new CodePropertyReferenceExpression { 
                    TargetObject = new CodeTypeReferenceExpression(type),
                    PropertyName = "Auto"
                };

            double d = 0;
            bool isStar = false;
            if (strValue.EndsWith("*"))
            {
                int length = strValue.Length;
                if (length > 1)
                {
                    double.TryParse(strValue.Substring(0, length - 1), out d);
                }
                isStar = true;
            }
            else
            {
                d = double.Parse(strValue); 
            }
            CodeObjectCreateExpression obj = new CodeObjectCreateExpression
            { 
                    CreateType = new CodeTypeReference(type)
            };
            obj.Parameters.Add(new CodePrimitiveExpression(d));
            obj.Parameters.Add(new CodePropertyReferenceExpression
            {
                PropertyName = isStar ? "Star" : "Pixel",
                TargetObject = new CodeTypeReferenceExpression
                {
                    Type = new CodeTypeReference("System.Windows.GridUnitType")
                }
            });
            return obj;
        }
        #endregion



    }
}
